from flask import Flask, session, redirect, url_for, escape, request, jsonify, Response, make_response
from service.AirControllerService import air_controller_service
from Tool.DBTool import DBTool
from Tool.ParamCheck import *
from Tool.Session import *
import traceback
from flask_cors import *
import datetime
import base64
from Tool.Sensor import get_tem_and_hum
from Tool.utils import Search,FileUtils,VideoInfo,DownloadVideo
import _thread

app = Flask(__name__)
# CORS(app, supports_credentials=True)  # 设置跨域
CORS(app, supports_credentials=True)

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

search = Search()
fileUtils = FileUtils('/home/pi/tomcat/webapps/ROOT')
info = VideoInfo()

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.after_request
def after_request(res):
    resp = make_response(res)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS'
    #resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, auth, Content-Length, Authorization, Accept, X-Requested-With'
    resp.headers['Access-Control-Allow-Credentials'] = 'true'
    resp.headers["Access-Control-Expose-Headers"] = "auth"
    resp.headers['Content-Type'] = 'application/json;charset=utf-8'
    return resp


@app.route('/login', methods=["POST"])
def login():
    # session.permanent = True
    # app.permanent_session_lifetime = datetime.timedelta(days=30)
    if request.method == 'POST':
        json_data = request.get_json()
        username = json_data['username']
        password = json_data['password']

        if check_username(username) == False or check_password(password) == False:
            return jsonify({"code": "400", "msg": "用户名或密码错误", "data": None})

        db = DBTool()
        sql = "select * from user where username=?"
        ob = [(username)]
        result = db.executeQuery(sql, ob)
        db_password = ""
        for s in result:
            db_password = s[2]
        db.close()
        if db_password == password:       
            # session['username'] = username
            # print(session)
            # print(session)
            resp = make_response(jsonify({"code": "200", "msg": "登录成功", "data": None}))
            # resp.set_cookie("user", "user")
            resp.headers["auth"] = set_auth(username)
            return resp

        return jsonify({"code": "400", "msg": "用户名或密码错误", "data": None})


@app.route('/air_controller', methods=['POST'])
def air_controller():
    if not check_auth(request.headers["auth"]):
        return jsonify({"code": "400", "msg": "Session错误", "data": None})
    try:
        # TODO: 校验数据
        json_data = request.get_json()
        state = json_data['state']
        mode = json_data['mode']
        tem = json_data['tem']
        air_controller_service(state, mode, tem)
    except Exception as e:
        return jsonify({"code": "400", "msg": traceback.format_exc(), "data": None})
    return jsonify({"code": "200", "msg": None, "data": None})

@app.route("/get_hum_and_tem", methods=["GET"])
def get_hum_and_tem():
    # try:
    #     auth = request.headers["auth"]
    #     if not check_auth(auth):
    #         return jsonify({"code": "400", "msg": "Session错误", "data": None})   
    # except Exception as e:
    #     return jsonify({"code": "400", "msg": traceback.format_exc(), "data": None})
    
    hum_and_tmp = get_tem_and_hum()
    result = {}
    result["humidity"] = int(hum_and_tmp[0])
    result["temperature"] = int(hum_and_tmp[1])

    return jsonify({"code": "200", "msg": None, "data": result})

@app.route('/get_sensor_info', methods=['GET'])
def get_sensor_info():
    # try:
    #     auth = request.headers["auth"]
    # except Exception as e:
    #     return jsonify({"code": "400", "msg": traceback.format_exc(), "data": None})
        
    # if not check_auth(auth):
    #     return jsonify({"code": "400", "msg": "Session错误", "data": None})
    try:
        start = request.args.get('start')
        end = request.args.get('end')
        start += " 00:00:00"
        end += " 23:59:59"
        print("select info from " + start + " to " + end)
        db = DBTool()
        sql = "select * from tem where date>=? and date <=?"
        ob = [(start), (end)]
        result = db.executeQuery(sql, ob)
        data = []
        for s in result:
            # print(s)
            tmp = {},
            s = list(s)
            tmp[0]["id"] = s[0]
            tmp[0]["date"] = s[1]
            tmp[0]["temperature"] = s[2]
            tmp[0]["humidity"] = s[3]
            tmp[0]["brightness"] = s[4]
            data.append(tmp[0])
    except Exception as e:
        return jsonify({"code": "400", "msg": traceback.format_exc(), "data": None})
    return jsonify({"code": "200", "msg": None, "data": data})


@app.route('/searchVideo', methods=['GET'])
def searchVideo():
    keyword = request.args.get('keyword')
    result = search.getSearchVideoList(keyword)
    return jsonify({"code": "200", "msg": '搜索成功', "data": result})


@app.route('/getVideoDetail', methods=['GET'])
def getVideoDetail():
    url = request.args.get('url')
    result = search.getVideoDetail(url)
    return jsonify({"code": "200", "msg": '请求成功', "data": result})


@app.route('/downloadVideo', methods=['GET'])
def downloadVideo():
    name = request.args.get('name')
    url = request.args.get('url')
    processNum = int(request.args.get('processNum'))

    if (fileUtils.isDownloaded(name)):
        return jsonify({"code": "200", "msg": '视频已缓存', "data": []})

    path = fileUtils.initFolder(name, url)
    _thread.start_new_thread(downloadThread, (path, url, processNum))
    return jsonify({"code": "200", "msg": '开始缓存', "data": []})


@app.route('/getCacheVideoList', methods=['GET'])
def getCacheVideoList():
    videos = fileUtils.getCacheVideoInfo()
    return jsonify({"code": "200", "msg": '请求成功', "data": videos})


def downloadThread(path, url, processNum):
    videos = info.getVideos(url)
    for video in videos:
        DownloadVideo(video, path, processNum).start()
        fileUtils.saveVideoInfo(path, video.get('name'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
